/**
 * 
 */
package com.bitBusy.manageyourriches.utilityClasses.adapters;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bitBusy.manageyourriches.R;
import com.bitBusy.manageyourriches.activity.EditExpenseRecordActivity;
import com.bitBusy.manageyourriches.activity.ViewExpensesActivity;
import com.bitBusy.manageyourriches.database.contactClasses.ExpenseDetails;
import com.bitBusy.manageyourriches.database.contactClasses.SpendingSubcategory;
import com.bitBusy.manageyourriches.database.managers.DatabaseInteractor;
import com.bitBusy.manageyourriches.database.managers.DateTimeManager;
import com.bitBusy.manageyourriches.utilityClasses.datastructures.CustomExpandableList;
import com.bitBusy.manageyourriches.utilityClasses.dialogboxes.DialogBoxPrompts;
import com.bitBusy.manageyourriches.utilityClasses.display.DisplayButtonValueUsers;
import com.bitBusy.manageyourriches.utilityClasses.display.DisplayMessages;

/**
 * Adapter for subcategories expandable list
 * @author SumaHarsha
 *
 */
public class SubcategoriesExpandableListAdapter  extends BaseExpandableListAdapter implements DisplayButtonValueUsers{

	/**Title for date/time*/
	private static final String DATETIMETITLE = "DATE/TIME";
	
	/**Payment info title*/
	private static final String PAYMENTINFOTITLE = "PAID BY";
			
    /** Amount title*/
	private static final String AMOUNTTITLE = "AMOUNT";
	
	/** Note title*/
	private static final String NOTETITLE = "NOTE";
	
	/** No expenditure*/
	private static final String NOEXPENDITURE = "No expenditure";
	
	/** Edit record*/
	private static final String EDITRECORD = "Edit record";
	
	/**Delete record*/
	private static final String DELETERECORD = "Delete record";
	
	/**Cancel*/
	private static final String CANCEL = "Cancel";
	
	/** record deleted*/
	private static final String RECORDDELETED = "Expense record deleted!";
	
	

	/**Context*/
	 private Context myContext;
	 
	 /**list of categories to be added*/
	 private List<SpendingSubcategory> mySubcategories;
	 
	 /**from date*/
	 private int myFromDate;
	 
	 /**to date*/
	 private int myToDate;
	 
	 /**DB Intereactor*/
	 private DatabaseInteractor myDBInteractor;
		
	 /** Current group position*/
	 private int myGroupPosition;
	
	 /** Current child position*/
	 private int myChildPosition;
	 
	 /** my list*/
	 private CustomExpandableList myList;
	 
	 /** Categories adapter associated with this subcategory list*/
	 private CategoriesExpandableListAdapter myCategoriesListAdapter;
	 
	 /** categories group position*/
	 private int myCategoriesGroupPosition;
	 
	 /** Categories adapter this belongs to*/
	// private CategoriesExpandableListAdapter myCategoriesListAdapter;
	
	 
	 /**Constructor
	 * @param the_categoriesExpandableListAdapter 
	 * @param the_categoriesGroupPosition 
	 * @param the_list */
	 public SubcategoriesExpandableListAdapter(Context the_context, 
			 CategoriesExpandableListAdapter the_categoriesExpandableListAdapter, int the_categoriesGroupPosition, CustomExpandableList the_list, List<SpendingSubcategory> subcategories, int the_fromDate, int the_toDate){
		 myContext = the_context;
		 mySubcategories = subcategories;
		 myDBInteractor = myContext!=null?new DatabaseInteractor(myContext):null;
		 myFromDate = the_fromDate;
		 myToDate = the_toDate;
		 myList = the_list;
		 myCategoriesListAdapter = the_categoriesExpandableListAdapter;
		 myCategoriesGroupPosition = the_categoriesGroupPosition;
	 }
	  
	 @Override
	 public Object getChild(int the_groupPosition, int the_childPosition) {
		 
		 List<ExpenseDetails> expenses = mySubcategories.get(the_groupPosition).getExpenses(myContext, myFromDate, myToDate);
		 if (expenses==null || expenses.size() == 0)
		 {
			 return NOEXPENDITURE;
		 }
		 else if (the_childPosition == 0)
		 {
			 return new ChildTitle(DATETIMETITLE, PAYMENTINFOTITLE, AMOUNTTITLE, NOTETITLE );
		 }
		 else
		 {
			 return expenses.get(the_childPosition-1);
		 }
	 }
	 
	 @Override
	 public long getChildId(int the_groupPosition, int the_childPosition) {
		 return the_childPosition;
		 }
	 
	 @Override
	 public View getChildView(int the_groupPosition, int the_childPosition, boolean isLastChild, 
	   View the_view, ViewGroup the_parent) {
		 
	   LayoutInflater infalInflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	   the_view = infalInflater.inflate(R.layout.amount_date_payment_details_row, null);
	   LinearLayout layout = (LinearLayout)the_view.findViewById(R.id.amountdetailsrow_layout);
	   layout.setLayoutParams(new LinearLayout.LayoutParams(the_parent.getWidth(), LayoutParams.WRAP_CONTENT));

	   Object listitem = getChild(the_groupPosition, the_childPosition);

	    ImageButton edit = (ImageButton) the_view.findViewById(R.id.viewExpenses_editDeleteImg);
		 TextView dateTime = (TextView) the_view.findViewById(R.id.amountDetails_dateTime);
		 TextView paymentInfo = (TextView) the_view.findViewById(R.id.amountDetails_paymentMethod);
		 TextView amount = (TextView) the_view.findViewById(R.id.amountDetails_amount);
		 TextView note = (TextView) the_view.findViewById(R.id.amountDetails_note);
		if (the_childPosition % 2 == 1)
		 {
			 dateTime.setBackgroundColor(Color.LTGRAY);
			 paymentInfo.setBackgroundColor(Color.LTGRAY);
			 amount.setBackgroundColor(Color.LTGRAY);
			 note.setBackgroundColor(Color.LTGRAY);
		 }

	  if (listitem instanceof ExpenseDetails)
	  {
		
	    setEditListener(edit,the_groupPosition, the_childPosition, this);
		ExpenseDetails expense = (ExpenseDetails) listitem;
		String date = DateTimeManager.parseForUserDate(DateTimeManager.getDate(expense.getDateTime()));	
		String time = DateTimeManager.getTime(expense.getDateTime());	

	    dateTime.setText( date + " " + time);
	   paymentInfo.setText(expense.getPaymentMethod());	
	   amount.setText(String.valueOf(expense.getAmount()));
	   note.setText(expense.getNote());
	  }
	  
	  else if(listitem instanceof ChildTitle)
	  {
		  ChildTitle title = (ChildTitle) listitem;
		  int textColor = myContext.getResources().getColor(R.color.indianRed);
		  
		  edit.setVisibility(View.INVISIBLE);
		  
		  dateTime.setText(title.getDateHeader());
		  dateTime.setTextColor(textColor);
		  
		  paymentInfo.setText(title.getPaymentInfoHeader());
		  paymentInfo.setTextColor(textColor);
		  
		  amount.setText(title.getAmountHeader());
		  amount.setTextColor(textColor);
		  
		  note.setText(title.getNoteHeader());	
		  note.setTextColor(textColor);
	  }
	  
	  else if(listitem instanceof String)
	  {
		  edit.setVisibility(View.INVISIBLE);

		  dateTime.setText(listitem.toString());
		  
		  paymentInfo.setVisibility(View.INVISIBLE);
		  
		  amount.setVisibility(View.INVISIBLE);
		  
		  note.setVisibility(View.INVISIBLE);
	
	  }
	  
		  return the_view;
	 }

	/* (non-Javadoc)
	 * @see android.widget.ExpandableListAdapter#getChildrenCount(int)
	 */
	@Override
	public int getChildrenCount(int the_groupPosition) {
		 List<ExpenseDetails> expenses = mySubcategories.get(the_groupPosition).getExpenses(myContext, myFromDate, myToDate);
		 return  (expenses==null?1:expenses.size()+1);

	}

		/* (non-Javadoc)
	 * @see android.widget.ExpandableListAdapter#getGroup(int)
	 */
	@Override
	public SpendingSubcategory getGroup(int the_groupPosition) {
		return mySubcategories.get(the_groupPosition);
	}

	/* (non-Javadoc)
	 * @see android.widget.ExpandableListAdapter#getGroupCount()	 */
	@Override
	public int getGroupCount() {
		return mySubcategories.size();
	}

	/* (non-Javadoc)
	 * @see android.widget.ExpandableListAdapter#getGroupId(int)
	 */
	@Override
	public long getGroupId(int the_groupPosition) {
		return the_groupPosition;
	}

	/* (non-Javadoc)
	 * @see android.widget.ExpandableListAdapter#getGroupView(int, boolean, android.view.View, android.view.ViewGroup)
	 */
	@Override
	public View getGroupView(int the_groupPosition, boolean isExpanded,
			View the_convertView, ViewGroup the_parent) {
		
		SpendingSubcategory subcategory = (SpendingSubcategory) getGroup(the_groupPosition);
		  if (the_convertView == null) {
		   LayoutInflater inf = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		   the_convertView = inf.inflate(R.layout.category_details_row, null);
		  }
		//  RelativeLayout layout = (RelativeLayout) the_convertView.findViewById(R.id.categoryrelativelayout);
		 // layout.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

		 ImageView subcategoryImg = (ImageView) the_convertView.findViewById(R.id.expandableList_Image);
		 subcategoryImg.setImageResource(subcategory.getImageID());
		 
		 String name = subcategory.getName();
		 TextView subcategoryName = (TextView) the_convertView.findViewById(R.id.expandableList_DescText);
		 subcategoryName.setText(name);
		 
		 double amount = myDBInteractor != null?myDBInteractor.getTotalSpentSubcategory(subcategory.getParentCategory(),
				 name, myFromDate, myToDate):0;		 
		 TextView subcategoryAmt = (TextView) the_convertView.findViewById(R.id.expandableList_AmtText);
		 subcategoryAmt.setText(String.valueOf(amount));
		 subcategoryAmt.setTextColor(Color.BLUE);
		 
		 the_convertView.setBackgroundColor(myContext.getResources().getColor(R.color.nonPinkLavendarBlush));   
		  return the_convertView;
		 }

	/* (non-Javadoc)
	 * @see android.widget.ExpandableListAdapter#hasStableIds()
	 */
	@Override
	public boolean hasStableIds() {
		return true;
	}

	/* (non-Javadoc)
	 * @see android.widget.ExpandableListAdapter#isChildSelectable(int, int)
	 */
	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}
	
	/**
	 * Method to set listener for edit button
	 * @param the button
	 */
	private void setEditListener(ImageButton the_button, final int the_groupPosition, final int the_childPosition, final DisplayButtonValueUsers the_caller)
	{
		if (the_button != null)
		{
			
			the_button.setOnClickListener(new OnClickListener() { 
				@Override
				public void onClick(View the_view) {
					myGroupPosition = the_groupPosition;
					myChildPosition = the_childPosition;
					  DisplayMessages.displayDialogWithThreeButtonsOnly(myContext, the_caller,
							  DialogBoxPrompts.DIALOGEDITTITLE.getPrompt(), EDITRECORD, DELETERECORD, CANCEL);
				}

			});
		}
	} 
	
	/* (non-Javadoc)
	 * @see com.bitBusy.manageyourriches.utilityClasses.display.DisplayButtonValueUsers#getButtonClickOnDialog(int)
	 */
	@Override
	public void getButtonClickOnDialog(Button the_button) {
		if (the_button != null)
		{
			String buttonText = the_button.getText().toString();
			SpendingSubcategory subcategory = getGroup(myGroupPosition);
			String subcategoryName = subcategory.getName();
			String categoryName = subcategory.getParentCategory();
			Object expense = getChild(myGroupPosition, myChildPosition);
			
			if (expense instanceof ExpenseDetails)
			{
				if (buttonText.equals(EDITRECORD))
				{
					Activity currActivity = (Activity)myContext;
					Intent intent = new Intent(currActivity, EditExpenseRecordActivity.class);
					intent.putExtra(ViewExpensesActivity.DATE_CHOSEN, DateTimeManager.getDate(((ExpenseDetails) expense).getDateTime()));
					intent.putExtra(ViewExpensesActivity.TIME_CHOSEN,  DateTimeManager.getTime(((ExpenseDetails) expense).getDateTime()));
					intent.putExtra(ViewExpensesActivity.AMOUNT_CHOSEN, String.valueOf(((ExpenseDetails) expense).getAmount()));
					intent.putExtra(ViewExpensesActivity.CATEGORY_CHOSEN, categoryName);
					intent.putExtra(ViewExpensesActivity.SUBCATEGORY_CHOSEN, subcategoryName);
					intent.putExtra(ViewExpensesActivity.PAYMENTMETHOD_CHOSEN, ((ExpenseDetails) expense).getPaymentMethod());
					intent.putExtra(ViewExpensesActivity.NOTE_CHOSEN, ((ExpenseDetails) expense).getNote());
					currActivity.startActivity(intent);
				}
				
				if (buttonText.equals(DELETERECORD) &&
						myDBInteractor.deleteRecord(categoryName, subcategoryName, (ExpenseDetails)expense))
				{
					refreshChildren();
				 	refresh();

					Toast.makeText(myContext.getApplicationContext(), RECORDDELETED, Toast.LENGTH_LONG).show();
				}
			}
			 	
		}
		
	}
	
	/**Refresh group view*/
	private void refresh()
	{
		notifyDataSetChanged();
		myCategoriesListAdapter.updateGroup(myCategoriesGroupPosition, myGroupPosition);
		ViewExpensesActivity currentActivity = (ViewExpensesActivity) myContext;
		currentActivity.setTotalSum();
		myList.expandGroup(myGroupPosition);
	}		


	/**Refresh children*/
	private void refreshChildren()
	{
		  mySubcategories.get(myGroupPosition).getExpenses(myContext, myFromDate, myToDate).remove(myChildPosition-1);

	}
	 
	
	
	
	/**Class for title*/
	 static class ChildTitle
	{
		
		/**Date header*/
		private static String myDateHeader;
		
		/**Payment Info Header*/
		private static String myPaymentInfoHeader;
		
		/**Amount header*/
		private static String myAmountHeader;
		
		/**Note header*/
		private static String myNoteHeader;
		
		
		/**
		 * Constructor
		 * @param the_dateTimeHeader
		 * @param the_paymentInfoHeader
		 * @param the_amountHeader
		 * @param the_noteHeader
		 */
		 ChildTitle(String the_dateTimeHeader, String the_paymentInfoHeader, String the_amountHeader, String the_noteHeader)
		 {
			 myDateHeader = the_dateTimeHeader;
			 myPaymentInfoHeader = the_paymentInfoHeader;
			 myAmountHeader = the_amountHeader;
			 myNoteHeader = the_noteHeader;
		 }
		 
		 /**Getters*/
		 
		 public String getDateHeader()
		 {
			 return myDateHeader;
		 }
		 
		 public String getPaymentInfoHeader()
		 {
			 return myPaymentInfoHeader;
		 }
		 public String getAmountHeader()
		 {
			 return myAmountHeader;
		 }
		 public String getNoteHeader()
		 {
			 return myNoteHeader;
		 }
		 
		 
	}
  }
	 


